package nuc.edu.tlias.aop;

import lombok.extern.slf4j.Slf4j;
import nuc.edu.tlias.mapper.OperateLogMapper;
import nuc.edu.tlias.pojo.OperateLog;
import nuc.edu.tlias.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect2 {
    @Autowired
    OperateLogMapper operateLogMapper;

    @Around("@annotation(nuc.edu.tlias.anno.Log)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();

        long cust = endTime - startTime ;

        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getEmoId());

        operateLog.setOperateTime(LocalDateTime.now());

        operateLog.setClassName(joinPoint.getTarget().getClass().getName());

        operateLog.setMethodName(joinPoint.getSignature().getName());

        operateLog.setMethodParams(Arrays.toString( joinPoint.getArgs()));//获取到的是一个数组，需要把数组转换为字符串

        operateLog.setReturnValue(result.toString());

        operateLog.setCostTime(cust);

        operateLogMapper.insert(operateLog);

        return result;
    }

    //获取员工id
    public Integer getEmoId(){
        Integer i = CurrentHolder.getCurrentId();
        return i;

    }

}
